<?php
$width = null;
$height = null;
$color = "f0f0f0";
$type = "webp";


if (isset($_GET['w']) && isset($_GET['h'])) {
    $width = $_GET['w'];
    $height = $_GET['h'];
    if ($height <= 9999 && $width <= 9999) {
        if (isset($_GET['type'])) {
            if ($_GET['type'] == "png" || $_GET['type'] == "jpg" || $_GET['type'] == "jpeg") {
                $type = $_GET['type'];
            }
        }

        if (isset($_GET['c']) && (strlen($_GET['c']) === 6 || strlen($_GET['c']) === 3)) {
            $bg = strtoupper($_GET['c']);
        } else {
            $bg = strtoupper($color);
        }

        if (strlen($bg) === 3) {
            $bg = strtoupper($bg[0].$bg[0].$bg[1].$bg[1].$bg[2].$bg[2]);
        }

        list($r, $g, $b) = sscanf($bg, "%2x%2x%2x"); //like c scanf
        // Create the image
        $im = imagecreatetruecolor($width, $height);

        // Create some colors
        $white = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        $black = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, $width, $height, $white);
        // Replace path by your own font path
        $font = __DIR__.'/font/PangMen.ttf';
        $pos = imagettfbbox($height*0.15, 0, $font, $_GET['text']);
        $text_height = $pos[1];
        $text_width = $pos[4];
        // Add some shadow to the text
        imagettftext($im, $height*0.15, 0, $width/2-$text_width/2, $height/2+$text_height/2+5, $black, $font, $_GET['text']);

        switch ($type) {
            case "png": 	header("Content-type: image/png");
                imagepng($im);
                break;
            case "jpg":
                case "jpeg": 	header("Content-type: image/jpeg");
                    imagejpeg($im);
                    break;
                case "webp":
                    header("Content-type:image/webp");
                    imagewebp($im);
                    break;
        }

        imagecolordeallocate($text_color);
        imagecolordeallocate($background);
        imagedestroy($im);
    } else {
        echo "Requested size is too big!";
    }
}